<?php
/**
 * app端 个人中心 客户信息管理
 * Author: lyun
 * Date: 2018/12/10
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Api\V1\App\Customers;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Customers\UpdateCustomerRequest;
use App\Http\Requests\Customers\UpdatePasswordRequest;
use App\Http\Services\Api\V1\App\Product\OrderService;
use App\Models\Customers\Customer;
use App\Services\EasySms\EasySmsService;
use App\Services\Utils\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class CustomerController extends ApiController
{
    /**
     * app端 更新客户的信息
     *
     * @param UpdateCustomerRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function updateCustomer(UpdateCustomerRequest $request)
    {
        /** @var Customer $customer */
        $customer = Guard::customer();
            $this->checkUpdateTelephoneExist($request, $customer);

        $customer_data = $this->assembleCustomerData($request);
        $updated = $customer->update($customer_data);

        return $this->response(compact('updated'));
    }

    /**
     *  app端 更新客户的密码
     *
     * @param UpdatePasswordRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function updatePassword(UpdatePasswordRequest $request)
    {
        /** @var Customer $customer */
        $customer = Guard::customer();

        $credentials = $this->getCredentials($request, $customer);

        /**
         * @see JWTGuard::validate()
         */
        $validate = Auth::guard(Customer::GUARD_NAME)->validate($credentials);

        $this->checkIsTrue($validate, trans('checker.password_verify_check'));

        $updated = $customer->update(['password' => Hash::make($request->password)]);

        return $this->response(compact('updated'));
    }

    /**
     * @param UpdateCustomerRequest $request
     * @return array
     */
    private function assembleCustomerData(UpdateCustomerRequest $request)
    {
        $data = [
            'fullname'  => $request->fullname,
            'email'     => $request->email,
            'telephone' => $request->telephone,
            'dial_code' => $request->dial_code
        ];

        if (is_file($request->image)) {
            $data['image'] = $request->image;
        }

        return $data;
    }

    /**
     * @param UpdatePasswordRequest $request
     * @param Customer $customer
     * @return array
     * @throws \Exception
     */
    private function getCredentials(UpdatePasswordRequest $request, Customer $customer)
    {
        $email = $customer->email;
        $telephone = $customer->telephone;
        $password = $request->old_password;

        if ($email) {
            return compact('email', 'password');
        } else if ($telephone) {
            return compact('telephone', 'password');
        } else {
            $this->checkUnless(true, trans('checker.customer_account_error'));
        }
    }

    /**
     * @return array|\Illuminate\Http\Response
     */
    public function showInfo()
    {
        $customer = Guard::customer();
        // jwt token 不应在 customer 中返回，登录接口错误的使用 customer 结构返回 jwt token，App已在使用
        $customer->addHidden('jwt_token', 'token', 'code', 'salt');

        return $this->response(compact('customer'));
    }

    /**
     * app个人中心，返回订单类型的统计数量。
     *
     * @return array|\Illuminate\Http\Response
     */
    public function indexOrderStatistics()
    {
        $order_statistics = (new OrderService)->getOrderStatistics();

        return $this->response(compact('order_statistics'));
    }

    /**
     * @param UpdateCustomerRequest $request
     * @param Customer $customer
     *
     * @throws \App\Exceptions\ApiAbstractException
     */
    private function checkUpdateTelephoneExist(UpdateCustomerRequest $request, Customer $customer): void
    {
        $telephone = $request->telephone;
        $dial_code = $request->dial_code;
        // 检测手机号和国家区号是否唯一
        $this->checkUnless(
            (new Customer)
                ->where(compact('telephone', 'dial_code'))
                ->where('customer_id', '<>', $customer->customer_id)
                ->exists(),
            trans('customer.phone_exist')
        );
    }
}
